import Joi from "joi";
import { RowDataPacket } from "mysql2";
import { getDB } from "~/server/utils/db/mysql/index";
import { getLoginUid, responseJson } from "~/server/utils/helper/index";
/**
 * 1、判断用户是否登录
 * 2、已登录获取用户文章
 */

export default defineEventHandler(async (event) => {
  // 1、判断用户是否登录
  let uid = getLoginUid(event);
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请登录", {});
  }

  const params = await getQuery(event);

  // 数据校验
  const schema = Joi.object({
    noteId: Joi.number().required(),
  });
  try {
    await schema.validateAsync(params);
  } catch (error) {
    return responseJson(1, "参数错误", {});
  }

  const con = getDB();

  try {
    const [rows] = await con.query<RowDataPacket[]>(
      "SELECT * FROM `notes` WHERE `id`=? AND `uid`=?",
      [params.noteId, uid]
    );
    
    if (Array.isArray(rows) && rows.length === 0) {
      return responseJson(1, "文章不存在或无权访问", {});
    }
    
    return responseJson(0, "获取成功", {
      list: {
        id: rows[0].id,
        title: rows[0].title,
        content_md: rows[0].content_md,
        state: rows[0].state,
      },
    });
  } catch (error) {
    // 记录错误详情以便调试
    console.error("获取文章详情失败错误详情:", error);
    if (error instanceof Error) {
      console.error("错误消息:", error.message);
      console.error("错误堆栈:", error.stack);
    }
    return responseJson(1, "获取失败", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
